package ca.etsmtl.log660.businessLogic;
import ca.etsmtl.log660.entity.Client;
import ca.etsmtl.log660.entity.Forfait;


import ca.etsmtl.log660.configuration.SessionFactoryHelper;
import org.hibernate.SessionFactory;
import org.hibernate.Session;

import java.util.*;


public class ConnexionController{   
   private ConnexionController(){ 

   } 
   
   public static ConnexionController getInstance() { 
      if (instance == null) { 
         instance = new ConnexionController(); 
      } 
      return instance; 
   }
   
   public boolean ValideAuthentification(String courriel, String motDePasse){ 
   		Session session = SessionFactoryHelper.getSessionFactory().openSession();
		session.beginTransaction();
		List lesClients = session.createQuery("From Client C Where C.Courriel = '" + courriel + "' and " +
							 				  "C.MotDePasse = '" + motDePasse + "'").list();			
		if(lesClients.size() == 1){
			Iterator iClient = lesClients.iterator(); 
			client = (Client) iClient.next();
			session.getTransaction().commit();
			session.close();
			loadForfaitLocationMax();	
			return true;
		}
		return false;
   }

   private Client client;
   private Forfait forfait;   

   public Client getClient(){
   		return client;
   } 
   
   public Forfait getForfait(){
   		return forfait;
   }
   
   private void loadForfaitLocationMax(){
   	   	Session session = SessionFactoryHelper.getSessionFactory().openSession();
		session.beginTransaction();
		client.getNomForfait();
		List lesforfaits = session.createQuery("From Forfait F Where F.NomForfait = '" + client.getNomForfait() + "'").list();
		if(lesforfaits.size() == 1) {
			Iterator iForfait = lesforfaits.iterator(); 
			forfait = (Forfait) iForfait.next();
			session.getTransaction().commit();
			session.close();	
			if(forfait.getLocationMax() == -1){
				forfait.setLocationMax(1000000);
			}
		}
   }   

   private static ConnexionController instance; 
}
    